package com.cosmic.pizza.service.Impl;

import com.cosmic.pizza.dao.Impl.UserDaoImpl;
import com.cosmic.pizza.dao.UserDao;
import com.cosmic.pizza.exception.loginException;
import com.cosmic.pizza.pojo.User;
import com.cosmic.pizza.service.UserService;
import com.cosmic.pizza.util.MailUtils;
import com.cosmic.pizza.util.UuidUtil;

import javax.mail.MessagingException;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override
    public User login(String username, String password) throws loginException {
        User user = userDao.findUserByUsernameAndPassword(username, password);
        if (user == null){
            throw new loginException("账号/密码错误");
        } else if (user.getStatus().equals("N")){
            throw new loginException("账号未激活");
        }
        return user;
    }

    @Override
    public boolean register(User user) {
        // 生成激活码
        String code = UuidUtil.getUuid();
        // 1.调用dao保存用户
        user.setCode(code);
        user.setStatus("N");
        int i = userDao.saveUser(user);
        if (i > 0) {
            // 2.发送激活邮件
            String text = "请点击<a href='http://localhost:8080/Pizza_war_exploded/User/active?code=" + code + "'>这里</a>激活账号";
            String title = "这是一封激活邮件";
            try {
                MailUtils.sendMail(user.getEmail(), text, title);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean usernameIsExists(String username) {
        return userDao.findUserByUsername(username) != null;
    }

    @Override
    public boolean activeUser(String code) {
        int i = userDao.setUserStatus(code);
        return i > 0;
    }
}
